<?php
namespace Jammiest\SwigeCore\Console\Commands\Server;

use Symfony\Component\Console\Attribute\AsCommand;
use Jammiest\SwigeCore\Console\Commands\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Swoole\Process;

#[AsCommand(
    name: 'server:stop',
    description: '停止 Swoole 服务器'
)]
class StopCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $pidFile = storage_path('swoole.pid');

        if (!file_exists($pidFile)) {
            $output->writeln('<error>服务器未运行</error>');
            return Command::FAILURE;
        }

        $pid = (int)file_get_contents($pidFile);

        if (Process::kill($pid, SIGTERM)) {
            unlink($pidFile);
            $output->writeln('<info>服务器已停止</info>');
            return Command::SUCCESS;
        }

        $output->writeln('<error>停止服务器失败</error>');
        return Command::FAILURE;
    }
}